<?php
class StudentClassesController extends AppController {
    var $pageTitle = 'Kelas';

    function add() {
        $this->__setAdditionals();
        $this->__saving();
    }

    function edit($id = null) {
        if (!$id) {
          $this->Session->setFlash(__('Invalid parameter', true), 'error');
          $this->__redirect('index');
        }
        $this->set('id', $id);
        $this->set('ajaxURL', $this->webroot . 
            $this->params['controller'] . '/'
        );

        $this->__setAdditionals($id);
        $this->__saving($id);

        if (empty($this->data)) {
            $this->data = $this->{$this->modelName}->find('first', array(
                'conditions' => array("{$this->modelName}.id" => $id)
            ));

            if (!$this->data) {
                $this->Session->setFlash(__('Invalid parameter', true), 'error');
                $this->__redirect('index');
            }
        } else {
            $this->data[$this->modelName]['id'] = $id;
        }
    }

    function inline_edit($student_id = null) {
        $this->layout = 'ajax';
        Configure::write('debug', 0);

        $data = $this->params['form'];
        unset($data['id']);
        if (!$student_id) {
            $this->StudentClass->Student->create();
        } else {
            $this->StudentClass->Student->id = $student_id;
        }

        if ($this->StudentClass->Student->save($data)) {
            $result = 1;
        } else {
            $result = 0;
        }
        $this->set('result', $result);
    }

    function delete_students() {
        $this->layout = 'ajax';
        Configure::write('debug', 0);
        $this->autoRender = false;

        $ids = $this->params['form']['id'];
        $this->StudentClass->Student->deleteAll(array(
            'Student.id' => $ids
        ));
    }

    function student_detail($student_id = null) {
    }

    function student_payment($student_id = null) {
        Configure::write('debug', 0);
        $this->layout = 'iframe';

        $this->StudentClass->Student->Behaviors->attach('Containable');
        $student = $this->StudentClass->Student->find('first', array(
            'conditions' => array(
                'Student.id' => $student_id
            )
        ));
        $payments = array();
        foreach ($student['StudentPayment'] as $key => $val) {
            $payments[$val['semester']] = $val;
        }

        $semester = array(
          'I', 'II', 'III', 'IV', 'V', 'VI',
          'Semester Tambahan I',
          'Semester Tambahan II',
        );
        $this->set('student_id', $student_id);
        $this->set('student', $student);
        $this->set('semester', $semester);
        $this->set('payments', $payments);

        if (!empty($this->data)) {
            // delete all first
            $this->StudentClass->Student->StudentPayment->deleteAll(
                array('StudentPayment.student_id' => $student_id),
                true,
                true
            );
            $data = array();
            $i = 0;
            foreach ($this->data['StudentPayment'] as $semester => $d) {
                $data[$i] = $d;
                $data[$i]['semester'] = $semester;
                $data[$i]['student_id'] = $student_id;
                $i++;
            }

            if ($this->StudentClass->Student->StudentPayment->saveAll($data)) {
                $this->Session->setFlash('Berhasil menyimpan', 'success');
                $this->redirect(array('action' => 'student_payment', $student_id));
            } else {
                $this->Session->setFlash('Tidak berhasil menyimpan', 'error');
                $this->set('payments', $data);
            }
        }
    }

    function report_students_payment() {
        if (isset($this->params['url']['class']) && !empty($this->params['url']['class'])) {
            $this->layout = 'printhtml';

            App::import('Model', array('Student', 'StudentPaymentObligation'));
            $class = $this->StudentClass->find('first', array(
                'conditions' => array(
                    'StudentClass.id' => $this->params['url']['class']
                )
            ));
            $this->StudentPaymentObligation = new StudentPaymentObligation;
            $payment_obligation = $this->StudentPaymentObligation->find('first', array(
                'conditions' => array(
                    'StudentPaymentObligation.year_started' => $class['StudentClass']['year_started']
                )
            ));

            $this->Student = new Student;
            $this->Student->Behaviors->attach('Containable');
            $payments = $this->Student->find('all', array(
                'conditions' => array(
                    'Student.student_class_id' => $this->params['url']['class']
                ),
                'order' => 'Student.name ASC',
                'contain' => array(
                    'StudentPayment'
                )
            ));
            foreach ($payments as $k => $p) {
                $payments[$k]['I'] = array();
                $payments[$k]['II'] = array();
                $payments[$k]['III'] = array();
                $payments[$k]['IV'] = array();
                $payments[$k]['V'] = array();
                $payments[$k]['VI'] = array();
                $payments[$k]['Semester Tambahan I'] = array();
                $payments[$k]['Semester Tambahan II'] = array();
                $payments[$k]['dpp'] = array();
                $payments[$k]['total'] = 0;
                $payments[$k]['due'] =
                    $payment_obligation['StudentPaymentObligation']['spp']*6 +
                    $payment_obligation['StudentPaymentObligation']['dpp'];
                foreach ($p['StudentPayment'] as $pay) {
                    $payments[$k][$pay['semester']] = array(
                        'payment_date' => $pay['payment_date'],
                        'spp' => $pay['spp'],
                    );
                    $payments[$k]['total'] += $pay['spp'];
                    if ($pay['dpp']) {
                        $payments[$k]['dpp'][] = array(
                            'payment_date' => $pay['payment_date'],
                            'dpp' => $pay['dpp']
                        );
                    }
                    $payments[$k]['total'] += $pay['dpp'];
                }
                // subtract due with total
                $payments[$k]['due'] -= $payments[$k]['total'];
            }

            $this->set('class', $class);
            $this->set('payments', $payments);
            $this->set('payment_obligation',
                $payment_obligation['StudentPaymentObligation']['spp'] +
                $payment_obligation['StudentPaymentObligation']['dpp']
                );
            $this->set('romans', array(
                'I', 'II', 'III', 'IV', 'V', 'VI'
            ));
            
        } else { // show filters
            $_c = $this->StudentClass->find('all', array(
                'fields' => array('id', 'name', 'year_started'),
                'order' => 'name ASC, year_started ASC'
            ));
            $classes = array();
            foreach ($_c as $c) {
                $classes[$c['StudentClass']['id']] =
                    $c['StudentClass']['name'] . ' (Angkatan ' .
                    $c['StudentClass']['year_started'] . ')';
            }
            $this->set('student_classes', $classes);
            $this->render('report_students_payment_form');
        }
    }

    function __setAdditionals($id = null) {
        $study_programs = $this->StudentClass->StudyProgram->find('list');
        $this->set('study_programs', $study_programs);

        if ($id) {
            $students = $this->StudentClass->Student->find('all', array(
                'conditions' => array(
                    'Student.student_class_id' => $id
                )
            ));

            $this->set('students', $students);
        }
    }

    function __saving($id = null) {
        if ( !empty($this->data) ) {
            $messageFlashSuccess = 'Kelas berhasil disimpan';
            $messageFlashError = 'Kelas tidak dapat disimpan';

            if ( $id ) {
                $this->{$this->modelName}->id = $id;
            } else {
                $this->{$this->modelName}->create();
            }
            $data = $this->data;

            // convert year
            $year_started = $this->data['StudentClass']['year_started']['year'];
            $this->data['StudentClass']['year_started'] = $year_started;

            if ($this->{$this->modelName}->save($this->data)) {
                $error = false;
                // on editing we don't need to save the student
                if ( !$id ) {
                    $ids  = array();
                    // set list_id, created_by and modified_by
                    foreach ( $data['Student'] as $key => $bd ) {
                        $bd['Student']['student_class_id'] = $this->{$this->modelName}->id;

                        $this->{$this->modelName}->Student->create();
                        if ( !$this->{$this->modelName}->Student->save($bd) ) {
                            $this->set('students', $data['Student']);
                            $error = true;

                            $this->{$this->modelName}->deleteAll(
                                array("{$this->modelName}.id" => $this->{$this->modelName}->id),
                                true,
                                true
                            );
                            break;
                        } else {
                            $ids[] = $this->{$this->modelName}->Student->id;
                        }
                    }
                }

                if ( !$error ) {
                    $this->Session->setFlash( $messageFlashSuccess, 'success');
                    $this->__redirect('index');
                } else {
                    $this->Session->setFlash( $messageFlashError, 'error');
                }
            } else { // failed saving lists
                $this->set('students', $data['Student']);
                $this->Session->setFlash($messageFlashError, 'error');
            }
        }
    }

    function getStudents($student_class_id) {
        Configure::write('debug', 0);
        $this->layout = 'ajax';

        $students = $this->StudentClass->Student->find('all', array(
            'conditions' => array(
                'Student.student_class_id' => $student_class_id
            )
        ));

        $this->set('students', $students);
    }
}
